package com.kiwilss.aopdemo.ui.paging

import androidx.paging.PagingSource
import java.lang.Exception

/**
 * @author : Administrator
 * e-mail : kiwilss@163.com
 * time   : 2021/02/02
 *  desc   :
 */
class PagingBeanSource : PagingSource<Int, PagingBean>() {
    var page = 1
    val mData by lazy { ArrayList<PagingBean>() }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, PagingBean> {
        return try {
            val page = params.key ?: 0
            getData()
            LoadResult.Page(
                data = mData,
                //如果可以往上加载更多就设置该参数，否则不设置
                prevKey = null,
                //加载下一页的key 如果传null就说明到底了
                nextKey = if (mData.size == mData.size) null else page + 1
            )

        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    fun getData() {
        var pagingBean: PagingBean
        for (i in 0..20) {
            pagingBean = PagingBean("name = $page + $i")
            mData.add(pagingBean)
        }
    }
}